import json
import time
import webapp2

from webapp2_extras.i18n import gettext as _

from apnetmodels.basicmodels import immeuble, fundraising
from google.appengine.api import users

from wtforms.ext.appengine.db import model_form

from common import functions

from BaseHandler import BaseHandler

class FundRaising(BaseHandler):
    def __init__(self, *args, **kwargs):
        super(FundRaising, self).__init__(*args, **kwargs)
        self.au = functions.GetAPNETUser()
        if not self.au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        self.fields = {
                       'period': _('Account period'), 'deadline': _('Due date'), 'type': _('Type'),
                       'desc': _('Description'), 'amount': _('Amount'), 'remarks': _('Remarks'),
                       'immeuble': _('Tenement'), 'summary_amount': _('Summary amount'), 'fundrised': _('Fundrised'),
                       'received': _('Received'), 'bankaccount': _('Bank account')
                       }
    
    def get(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)

    def post(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)
    
    def op_list(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        
        template_values = {
                           'title': _('Fundraising. %s' % imm.name),
                           'header': _('ATENET. Fundraising. %s' % imm.name),
                           'app_user': self.au,
                           'immeuble': imm,
                           'lurl': users.create_logout_url('/'),
                           'section': 'vie',
                           'leftmenu': 'fundraising',
                           'fields': self.fields
                           }

        template = self.jinja2.get_template('templates/fundraising_list.html')
        self.response.out.write(template.render(template_values))
    
    def op_list_json(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        
        query = imm.fundraising_set.order('period').order('deadline').run()
        fr = []
        for f in query:
            fr.append([unicode(f.period), functions.datetimeformat(f.deadline), unicode(f.type), unicode(f.desc), f.amount, str(f.key().id())])
        ret = {}
        ret['aaData'] = fr
        self.response.out.write(json.dumps(ret))
    
    def op_add(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        ok_message = ''
        FundRaisingForm = model_form(fundraising, exclude=['immeuble', 'lastchange_by', 'lastchange_date', 'commited'])
        
        if self.request.method == 'GET':
            form = FundRaisingForm()
            form['period'].query = imm.period_concept_set.filter('close_accounting =', False)
            form['bankaccount'].query = imm.bankaccount_set
        
        if self.request.method == 'POST':
            form = FundRaisingForm(self.request.POST)
            if form.validate():
                obj_fr = fundraising(
                                  period = form['period'].data,
                                  deadline = form['deadline'].data,
                                  type = form['type'].data,
                                  desc = form['desc'].data,
                                  amount = form['amount'].data,
                                  remarks = form['remarks'].data,
                                  bankaccount = form['bankaccount'].data,
                                  immeuble = imm,
                                  lastchange_by = self.au
                                  )
                obj_fr.put()
                while not obj_fr.is_saved():
                    time.sleep(1)
                
                ok_message = _('FundRaising was added.')
            form['period'].query = imm.period_concept_set.filter('close_accounting =', False)    
            form['bankaccount'].query = imm.bankaccount_set
            
        template_values = {'form': form, 'ok_message': ok_message, 'fields': self.fields}
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
    
    def op_edit(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        fr_id = kwargs.get('fr_id', -1) 
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        obj_fr = fundraising.get_by_id(int(fr_id))
        if not obj_fr:
            self.object_does_not_exist()
            return

        ok_message = ''
        alert_message = ''
        
        FundRaisingForm = model_form(fundraising, exclude=['immeuble', 'lastchange_by', 'lastchange_date', 'commited'])
        if self.request.method == 'GET':
            form = FundRaisingForm(obj=obj_fr)
            form['period'].query = imm.period_concept_set.filter('close_accounting =', False)
            form['bankaccount'].query = imm.bankaccount_set
            
        if self.request.method == 'POST':
            form = FundRaisingForm(self.request.POST)
            if form.validate():
                form.populate_obj(obj_fr)
                if not obj_fr.commited:
                    obj_fr.put()
                    ok_message = _('FundRaising was updated.')
                else:
                    alert_message = _("Fundraising commited and cannot be updated")

            form['period'].query = imm.period_concept_set.filter('close_accounting =', False)
            form['bankaccount'].query = imm.bankaccount_set
        
        template_values = {'form': form, 'ok_message': ok_message, 'fields': self.fields, 'alert_message': alert_message}
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
        
    def op_commit(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        fr_id = kwargs.get('fr_id', -1) 
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        fr = fundraising.get_by_id(int(fr_id))
        if not fr:
            self.object_does_not_exist()
            return
        
        ok_message = ''
        alert_message = ''
        info_message = ''
        
        if self.request.method == 'GET':
            if fr.commited:
                info_message = _('Fundraising request already commited')
            else:
                alert_message = _('Fundraising request will be commited and General Ledger will be updated')
            
        if self.request.method == 'POST':
            
            if fr.commited:
                info_message = _('Fundraising request already commited')
            else:
                res, msg = fr.update_general_ledger(self.au)
                if res:
                    fr.commited = True
                    fr.put()
                    ok_message = _(msg)
                else:
                    alert_message = _(msg)
                
        template_values = {
            'ok_message': ok_message,
            'alert_message': alert_message,
            'info_message': info_message,
            'fields': self.fields
        }
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
